package com.loyi.ams.gateway.hbmis.rest;

import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.loyi.ams.gateway.hbmis.dao.IDeviceDAO;
import com.loyi.ams.gateway.hbmis.dao.IRealDataDAO;
import com.loyi.cloud.hbmis.api.IDeviceService;
import com.loyi.cloud.hbmis.api.IRealDataService;
import com.loyi.cloud.hbmis.domain.Device;
import com.loyi.cloud.hbmis.domain.RealData;
import com.netflix.discovery.converters.Auto;

@RestController
@RequestMapping("realdata")
public class RealDataService implements IRealDataService {

	@Autowired
	private IRealDataDAO realDataDAO;

	@Autowired
	private IDeviceService deviceService;

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Override
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public void save(@RequestBody RealData data) {
		RealData exitData;
		List<Device> devices;
		long s;

		s = System.currentTimeMillis();

		// 通过设备编号查找监测点编号
		devices = deviceService.find(null, data.getDeviceid(), null, Arrays.asList(2));
		// devices.
		if (devices == null || devices.size() == 0) {
			logger.warn(String.format("无法找到对应监测点位,设备编号：%s", data.getDeviceid()));
			return;
		}
		data.setPtid(devices.get(0).getPtid());

		exitData = realDataDAO.find(data.getDatatime(), data.getPtid(), data.getPollcode());
		if (exitData == null) {
			realDataDAO.insert(data);
		} else {
			data.setDataid(exitData.getDataid());
			realDataDAO.update(data);
		}

		logger.info(String.format("分钟数据保存完毕，用时%sms", System.currentTimeMillis() - s));
	}

}
